package me.flyray.gate.utils;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;

import me.flyray.common.context.BaseContextHandler;
import com.netflix.zuul.context.RequestContext;

import lombok.extern.slf4j.Slf4j;

/**
 * @author Mu
 * @Description 
 * 请求路径过滤
 * */
@Configuration
@Slf4j
public class FilterUrlUtils {
	
	/**
	 * 忽略token拦截地址
	 * */
	@Value("${gate.token.ignore.startWiths}")
	private  String token_ignoreUrls;
	/**
	 * 签名拦截地址
	 * */
	@Value("${gate.sign.intercept_Urls}")
	private  String sign_interceptUrls;

	/**
	 * 请求路径起初地址
	 * */
	@Value("${zuul.prefix}")
	private  String zuulPrefix;
	/**
	 * 忽略签名拦截地址
	 * */
	@Value("${gate.sign.ignore.startWiths}")
	private  String sign_ignoreUrls;

	/**
	 * 过滤忽略地址
	 * @param type 0: 表示过滤忽略token地址；1: 表示过滤忽略签名地址；
	 * @return
	 */
	public  boolean filterIgnoreUrl(int type) {
		RequestContext ctx = RequestContext.getCurrentContext();
        HttpServletRequest request = ctx.getRequest();
        final String requestUrl = request.getRequestURI().substring(zuulPrefix.length());
        BaseContextHandler.setToken(null);
		boolean flag = false;
		if(0==type){
			for (String s : token_ignoreUrls.split(",")) {
				if (requestUrl.startsWith(s)) {
					return true;
				}
			}
		}
		if(1==type){
			for (String s : sign_ignoreUrls.split(",")) {
				if (requestUrl.startsWith(s)) {
					return true;
				}
			}
		}
		return flag;
	}

	/**
	 * 过滤拦截地址
	 * @param type 0: 表示过滤token拦截地址；1: 表示过滤签名拦截地址；
	 * @return
	 */
	public  boolean filterInterceptUrl(int type) {
		RequestContext ctx = RequestContext.getCurrentContext();
		HttpServletRequest request = ctx.getRequest();
		final String requestUrl = request.getRequestURI().substring(zuulPrefix.length());
		BaseContextHandler.setToken(null);
		boolean flag = false;
		if(0==type){
			for (String s : sign_interceptUrls.split(",")) {
				if (requestUrl.startsWith(s)) {
					return true;
				}
			}
		}
		if(1==type){
			for (String s : sign_interceptUrls.split(",")) {
				if (requestUrl.startsWith(s)) {
					return true;
				}
			}
		}
		return flag;
	}

}
